/**
 *
 * 旧版方法留档
 *
 */

var express = require('express')
var router = express.Router()
var config = require('../config.json')
var request = require('request')
var muilter = require('../multerUtil')
var upload = muilter.single('file')
var fs = require('fs')

//本地数据逻辑
if (config.local_data) {
  /**预设json数据文件读取逻辑
   * 通过表示路由路径 . 表示路由中的 / , # 表示自定义变量
   * 从router-data开始的路径表示路由的前缀
   * TODO 设置默认路由动态提取json文件，根据路由参数生成文件路径并进行读取
   */
  var dataList = []
  var routesList = []
  var dataFile = 'server/routes-data'
  $.walkFile(dataFile, dataList)
  for (let i in dataList) {
    let fl = dataList[i]
    let match = fl.match(/\/[^\/]+$/)
    if (match) {
      let name = match[0]
      let folder = fl.replace(dataFile, '').split('/')
      folder = folder.splice(0, folder.length - 1)
      let nameArr = name.split('.').slice(0, -1)
      let namePath = '/service/:app'
      let varCount = 0
      if (folder && folder.length) {
        namePath += folder.join('/')
      }
      for (let s in nameArr) {
        if (s > 0) namePath += '/'
        if (nameArr[s] === '#') {
          namePath += ':code_' + varCount++
        } else {
          namePath += nameArr[s]
        }
      }
      routesList.push({
        route: namePath,
        path: fl
      })
    }
  }
  // 生成路由函数
  for (let i in routesList) {
    let route = routesList[i]
    router.all(route.route, function (req, res) {
      res.send($.readJson(route.path))
    })
  }
}

if (config.remove_data) {
  router.all('/service/:app/*', upload, function (req, res) {
    var host = config.remote_host
    var data = req.body
    var type = req.get('Content-Type')
    var opts = {
      method: req.method,
      url: host + req.path,
      query: req.query,
      headers: {
        'Content-Type': req.get('Content-Type'),
        'content-length': req.get('Content-length')
      }
    }
    // opts.headers = req.headers
    if (data) {
      if (type) {
        if (type.indexOf('form') >= 0) {
          opts.formData = JSON.parse(JSON.stringify(data))
        } else if (type.indexOf('json') >= 0) {
          opts.body = data
          opts.json = true
        }
      } else {
        opts.body = data
        opts.json = true
      }
    }

    if (req.query) {
      var f = ''
      for (let i in req.query) {
        f += i + '=' + req.query[i] + '&'
      }
      if (f !== '') {
        f = f.slice(0, -1)
        opts.url += '?' + f
      }
    }

    if (opts.formData && req.file) {
      var r = request.post(config.remote_host + req.path, (err, resp, body) => {
        err && console.log(err)
        res.send(body)
      })
      var form = r.form()
      if (req.file) {
        form.append('file', fs.createReadStream(process.cwd() + '/' + req.file.path))
      }
    // opts=getUploadRequest()
    } else {
      var reqify = request(opts, function (error, response, body) {
        if (error) {
          console.error('TRANSMIT ERROR:' + error)
        }
        console.log('TRANSMIT DONE:' + req.path)
        res.send(body)
      })
      reqify
    // writeFile(reqify, 'Reuqeset.' + reqPath)
    }
  })
}
// 旧版上传逻辑
function getUploadRequest (req, opts) {
  opts.formData[req.file.fieldname] = fs.createReadStream(req.file.path)
  if (opts.formData) {
    opts = {
      formData: opts.formData,
      url: opts.url,
      headers: {
        'Content-Type': req.get('Content-Type')
      }
    }
  }
  return opts
}



module.exports = router
